import { Sema } from 'async-sema';
import $store from '@/store/index.js';
const emojiUtils = {
  // 获取表情列表的函数
  getEmojiList() {
    return new Promise((resolve, reject) => {
      uni.$api.common.emojilist({emoji_type: 'emoji'}).then(res => {
        if (res) {
          resolve(res.data);
        } else {
          reject('Failed to fetch emoji list');
        }
      }).catch(e => {
        reject(e);
      });
    });
  },

  // 下载并保存表情的函数
  downloadAndSaveEmoji(emoji, retryCount = 0) {
    return new Promise((resolve, reject) => {
      const attemptDownload = (attemptsLeft) => {
        uni.downloadFile({
          url: emoji.image_url,
          success: (downloadRes) => {
            if (downloadRes.statusCode === 200) {
              // 将下载的文件保存到本地
              uni.saveFile({
                tempFilePath: downloadRes.tempFilePath,
                success: (res) => {
                  // 保存成功后返回文件路径、名称和ID
                  resolve({
                    src: res.savedFilePath,
                    regName: emoji.regName,
                    id: emoji.id
                  });
                },
                fail: (err) => {
                  if (attemptsLeft > 0) {
                    attemptDownload(attemptsLeft - 1);
                  } else {
                    reject(err);
                  }
                }
              });
            } else {
              if (attemptsLeft > 0) {
                attemptDownload(attemptsLeft - 1);
              } else {
                reject('Failed to download emoji');
              }
            }
          },
          fail: (err) => {
            if (attemptsLeft > 0) {
              attemptDownload(attemptsLeft - 1);
            } else {
              reject(err);
            }
          }
        });
      };

      attemptDownload(retryCount);
    });
  },

  // 检查并下载表情的函数
  async checkAndDownloadEmojis() {
    try {
      const emojiListObject = await this.getEmojiList();
      // 将对象转换为数组
      const emojiList = Object.keys(emojiListObject).map(key => {
        return {
          regName: key,
          ...emojiListObject[key]
        };
      });
      // 获取本地已缓存的表情列表
      let localEmojis = uni.getStorageSync('local_Emojis') || [];
	  
	  // 用于存储新的 localEmojis，顺序与 emojiListObject 一致
	  let updatedLocalEmojis = [];
      const failedDownloads = [];
	  const semaphore = new Sema(5);  // 设置最大并发量为 5
	  
	  const downloadTasks = emojiList.map(async (emoji) => {
		await semaphore.acquire();  // 获取一个许可
		try {
		  const existingEmoji = localEmojis.find(localEmoji => localEmoji.regName == emoji.regName);

		  if (!existingEmoji) {
			// 本地没有这个表情，进行下载
			const emojiData = await this.downloadAndSaveEmoji(emoji);
			updatedLocalEmojis.push(emojiData);
			console.log('完成下载',emoji.id,emojiData);
			$store.commit('pushEmojis',emojiData)
		  } else {
			updatedLocalEmojis.push(existingEmoji);
		  }
		  
		} catch (downloadError) {
		  console.error(`Failed to download emoji ${emoji.id}:`, downloadError);
		  failedDownloads.push(emoji.id);
		} finally {
		  semaphore.release();  // 释放许可
		}
	  });
	  console.log(downloadTasks);
	  await Promise.all(downloadTasks);
	  
	  $store.commit('setEmojis',updatedLocalEmojis)
      // 更新本地存储
      uni.setStorageSync('local_Emojis', updatedLocalEmojis);

      if (failedDownloads.length > 0) {
        console.warn('Some emojis failed to download:', failedDownloads);
      }

    } catch (error) {
      console.error('Error checking and downloading emojis:', error);
    }
  },

  // 根据表情ID获取本地表情数据
  getLocalEmojiData(emojiId) {
    const localEmojis = uni.getStorageSync('localEmojis') || [];
    return localEmojis.find(localEmoji => localEmoji.id === emojiId) || null;
  }
};

export default emojiUtils;
